package com.goodving.guli.fragment;


import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.androidquery.AQuery;
import com.goodving.guli.R;
import com.goodving.guli.activity.GuliHardwareSettingActivity;
import com.goodving.guli.activity.MainFragmentActivity;
import com.goodving.guli.activity.ScaleActivity;
import com.goodving.guli.model.DailyStats;
import com.goodving.guli.model.DeviceSource;
import com.goodving.guli.model.StatsManagerWrapper;
import com.goodving.guli.service.StepMessage;
import com.goodving.guli.utility.C1057l;
import com.goodving.guli.utility.C1481u;
import com.goodving.guli.utility.Constants;
import com.goodving.guli.utility.LdlDate;
import com.goodving.guli.view.TotalStatsCircleView;

import java.util.ArrayList;
import java.util.List;

import name.bagi.levente.pedometer.StepService;

/**
 * Created by john on 2015/11/18.
 */
public class HomeFragment extends BaseFragment implements View.OnClickListener {

    private static final int MESSAGE_NOTIFICATION = 2;
    private static final int MESSAGE_UPDATE = 1;

    private LinearLayout btnScale;

    public static final String TAG;
    private AQuery mAQuery;
    private ViewPager mViewPagerDay;
    private MyPagerAdapter mViewPagerDayAdapter;
    private List<View> viewList;//view数组


//    private static DailyStatsByDay mDailyStatsByDay = DailyStatsByDay.getInstance();
//    private static DailyStats mDailyStats = mDailyStatsByDay.getDailyStatsByDay(mLdlDate);

    static {
        TAG = HomeFragment.class.getName();
    }
//    private DailyStats mDailyStats;
    private TotalStatsCircleView mStatsCircleView;

    private ListView mListView;
    private C1057l mListViewAdapter;
    private MyHandler mHandler;

    public void onClick(View view) {
        if (view.getId() == R.id.id_home_scale) {
            // here we need to check if customer ever bind a scale before, if yes, go to scale view directly.
            // other wise go to bind hardware setting activity.

            Intent intent = new Intent();
            if (!DeviceSource.hasBindWeight()) {
                intent.setClass(C1481u.getContext(), GuliHardwareSettingActivity.class);
            } else {
                intent.setClass(C1481u.getContext(), ScaleActivity.class);
            }
            startActivity(intent);
        }
    }

    public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {

        View inflate = layoutInflater.inflate(R.layout.fragment_home_viewpager, viewGroup, false);
        this.mAQuery = new AQuery(inflate);

//        this.mAQuery.id(R.id.scale_machine).clicked(C1481u.getContext(), "onClick");
        btnScale = (LinearLayout) inflate.findViewById(R.id.id_home_scale);
        btnScale.setOnClickListener(this);
        this.mViewPagerDay = (ViewPager) inflate.findViewById(R.id.homePageView);

        return inflate;
    }
    public void updateData(Message msg) {
//        Message msg = Message.obtain();
//        msg.what = Constants.STEPS_MSG;
        processMessage(msg);
    }

    class MyPagerAdapter extends PagerAdapter {

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0 == arg1;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return viewList.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position,
                                Object object) {
            // TODO Auto-generated method stub
            container.removeView(viewList.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // TODO Auto-generated method stub
            container.addView(viewList.get(position));


            return viewList.get(position);
        }
    }

    public void updateStatus() {

        Log.e(TAG, "=============updateStatus================");



        LdlDate tempLdlDate = LdlDate.m8856a().m8876i();
        DailyStats tempDailyStats = StatsManagerWrapper.getDailyStats(C1481u.getContext(), tempLdlDate);
        (mAQuery.id((int) R.id.text_runing_man)).text("" + tempDailyStats.getRunStep() + "步");
        (mAQuery.id((int) R.id.text_walking_man)).text("" + tempDailyStats.getWalkStep() + "步");

//            this.mDailyStats = dailyStats;
        if (this.mStatsCircleView != null) {
            this.mStatsCircleView.updateStatsCircle(tempDailyStats);
        }
        updateTimeLine();

    }

    public void updateTodayStats() {
        updateStatus();
    }

    public void processMessage(Message message) {
        switch (message.what) {
            case Constants.STEPS_MSG /*1*/:

                updateTodayStats();
//            case MESSAGE_NOTIFICATION /*2*/:
//                updateTodayNotification((StepMessage) message.obj);
            default:
        }
    }

    public void updateTodayNotification(StepMessage stepMessage) {
        if (this.mStatsCircleView != null) {
            this.mStatsCircleView.updateStepNotification(stepMessage);
        }
    }

    public void createFragment() {
        LdlDate tempLdlDate = LdlDate.m8856a().m8876i();
        DailyStats tempDailyStats = StatsManagerWrapper.getDailyStats(C1481u.getContext(), tempLdlDate);
//        if (this.mDailyStats == null) {
//            this.mDailyStats = new DailyStats(Parcel.obtain());
//        }
//        dailyStats.setStepCnt(1000);//TBD just for debug
        this.mStatsCircleView = new TotalStatsCircleView(getActivity(), tempDailyStats);

        viewList = new ArrayList<View>();// 将要分页显示的View装入数组中
        viewList.add(this.mStatsCircleView);
        mViewPagerDayAdapter = new MyPagerAdapter();
        mViewPagerDay.setAdapter(this.mViewPagerDayAdapter);


        (mAQuery.id((int) R.id.text_runing_man)).text("" + tempDailyStats.getRunStep() + "步");
        (mAQuery.id((int) R.id.text_walking_man)).text("" + tempDailyStats.getWalkStep() + "步");

        updateTimeLine();
    }


    public class MyHandler extends Handler {

        public void handleMessage(Message message) {
                HomeFragment.this.processMessage(message);
        }
    }

    public void onActivityCreated(Bundle bundle) {
        super.onActivityCreated(bundle);
        createFragment();
        Handler mHandler = new Handler() {
            @Override public void handleMessage(Message msg) {
                HomeFragment.this.processMessage(msg);
            }
        };
        this.mHandler = new MyHandler();
        ((MainFragmentActivity) getActivity()).mFragment = this;


    }

    public void onResume() {
        super.onResume();

    }
    private void updateTimeLine() {
        mViewPagerDayAdapter.notifyDataSetChanged();
    }

    private static StepService mService;

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mService = ((StepService.StepBinder)service).getService();

            mService.registerCallback(mCallback);
            mService.reloadSettings();

        }

        public void onServiceDisconnected(ComponentName className) {
            mService = null;
        }
    };

    // TODO: unite all into 1 type of message
    private StepService.ICallback mCallback = new StepService.ICallback() {
        public void stepsChanged(int value) {
            mHandler.sendMessage(mHandler.obtainMessage(Constants.STEPS_MSG, value, 0));
        }
        public void paceChanged(int value) {
            mHandler.sendMessage(mHandler.obtainMessage(Constants.PACE_MSG, value, 0));
        }
        public void distanceChanged(float value) {
            mHandler.sendMessage(mHandler.obtainMessage(Constants.DISTANCE_MSG, (int)(value*1000), 0));
        }
        public void speedChanged(float value) {
            mHandler.sendMessage(mHandler.obtainMessage(Constants.SPEED_MSG, (int) (value * 1000), 0));
        }
        public void caloriesChanged(float value) {
            mHandler.sendMessage(mHandler.obtainMessage(Constants.CALORIES_MSG, (int)(value), 0));
        }
    };

}
